package web;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import IO.SystemInfo;

import data.Show;

public class Downloader extends Thread 
{
	private Show show;
	
	public Downloader(Show s)
	{
		this.show = s;
		this.run();
	}
	
	public void run()
	{
		this.downloadTorrent();
	}
	
	public boolean downloadTorrent()
	{
		
		long loopTimeout = 1000 * 60 * 5; //5 minutes
		boolean wasSuccessful = true;
		String torrentFilename = show.getShowName();
		torrentFilename.replace(" ", ".");
		torrentFilename += " ";
		torrentFilename = torrentFilename + "s" + show.getSelectedSeason().getSeasonNumber();
		torrentFilename = torrentFilename + "e" + show.getEpisodeToDownload().getEpisodeNumber() + ".torrent";
		String torrentFullPath = SystemInfo.getTorrentDirectory() + torrentFilename;
		
		try
		{
			long start = System.currentTimeMillis();
			int bufferSize = 153600;//150kilobytes
			URL url = new URL(show.getEpisodeToDownload().getTorrentURL());
			url.openConnection();
			InputStream reader = url.openStream();
			
			FileOutputStream writer = new FileOutputStream(torrentFullPath);
			byte[] buffer = new byte[bufferSize];
			int totalBytesRead = 0;
			int bytesRead = 0;
			
			while ((bytesRead = reader.read(buffer)) > 0)
			{
				//Check if we timed out
				if ((System.currentTimeMillis() - start) > loopTimeout)
				{
					wasSuccessful = false;
					break;
				}
				
				writer.write(buffer, 0, bytesRead);
				buffer = new byte[bufferSize];
				totalBytesRead += bytesRead;
			}
			
			long downloadTime = System.currentTimeMillis() - start;
			if(wasSuccessful)
			{
				System.out.println("The torrent download completed in " + downloadTime/1000 + " seconds...\nBitchin!");
				//hot diggedy damn we downloaded it!  Better make that show go to the next episode
				show.goToNextEpisode();
			}
			else
			{
				System.out.println("Sonny couldn't download your torrent.  U mad?");
			}
			
			reader.close();
			writer.close();
		}
		catch (Exception e)
		{
			wasSuccessful = false;
			//will this need to cleanup the effed up torrent file?
		}
		return wasSuccessful;
	}
}
